import React, { useState, useEffect } from 'react';
import { Card, Button, Form, Space, message } from 'antd';
import { ProTable, ProColumns } from '@ant-design/pro-table';
import { DatePicker } from 'antd';
import { SearchOutlined } from '@ant-design/icons';
import { getWorkDetailByDeviceIds } from '../../request/workDetail';
import { WorkData } from '../../types/workDetail';



const { RangePicker } = DatePicker;

const WorkDetail: React.FC = () => {
  const [dataSource, setDataSource] = useState<WorkData[]>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const [form] = Form.useForm();

  // Initialize data
  useEffect(() => {
    // Load default data without date parameters
    fetchWorkDetailData();
  }, []);

  const fetchWorkDetailData = async (startDate?: string, endDate?: string) => {
    setLoading(true);
    try {
      const data = await getWorkDetailByDeviceIds(startDate, endDate);
      setDataSource(data);
    } catch (error) {
      console.error('Failed to fetch work detail data:', error);
      message.error('获取数据失败');
    } finally {
      setLoading(false);
    }
  };

  const columns: ProColumns<WorkData>[] = [
    {
      title: '作业编号',
      dataIndex: 'id',
      key: 'id',
    },
    {
      title: '车辆',
      dataIndex: 'vehicle',
      key: 'vehicle',
    },
    {
      title: '司机',
      dataIndex: 'driver',
      key: 'driver',
    },
    {
      title: '开始时间',
      dataIndex: 'startTime',
      key: 'startTime',
      valueType: 'dateTime',
    },
    {
      title: '结束时间',
      dataIndex: 'endTime',
      key: 'endTime',
      valueType: 'dateTime',
    },
    {
      title: '运输里程（米）',
      dataIndex: 'transportDistance',
      key: 'transportDistance',
    },
    {
      title: '起点经度',
      dataIndex: 'startLongitude',
      key: 'startLongitude',
    },
    {
      title: '终点经度',
      dataIndex: 'endLongitude',
      key: 'endLongitude',
    },
    {
      title: '起点纬度',
      dataIndex: 'startLatitude',
      key: 'startLatitude',
    },
    {
      title: '终点纬度',
      dataIndex: 'endLatitude',
      key: 'endLatitude',
    },
    {
      title: '状态',
      dataIndex: 'transportStatus',
      key: 'transportStatus',
      render: (_, record) => {
        // 1 represents valid, 0 represents invalid
        if (record.transportStatus === 1) {
          return <span style={{ color: 'green' }}>有效</span>;
        } else if (record.transportStatus === 0) {
          return <span style={{ color: 'red' }}>无效</span>;
        } else {
          return <span>未知</span>;
        }
      },
    },
    {
      title: '运输轨迹',
      // dataIndex: '',
      // key: '',
      render: (_) => (
       <Button 
          type="link" 
          href={`https://map.baidu.com/`}
          target="_blank"
        >
          查看
        </Button>
      ),
    },
  ];

  // Handle search
  const handleSearch = async (values: any) => {
    if (values.dateRange && values.dateRange.length === 2) {
      const [startDate, endDate] = values.dateRange;
      // Format dates to YYYY-MM-DD
      const startDateStr = startDate.format('YYYY-MM-DD');
      const endDateStr = endDate.format('YYYY-MM-DD');
      
      await fetchWorkDetailData(startDateStr, endDateStr);
    } else {
      // If no date range is selected, fetch without date parameters
      await fetchWorkDetailData();
    }
  };

  // Reset search
  const handleReset = async () => {
    // Reset form and fetch without date parameters
    form.setFieldsValue({ 
      dateRange: null
    });
    await fetchWorkDetailData();
  };

  return (
    <div>
      <div style={{ padding: '24px 0' }}>       
        <Card 
          variant="outlined"
          styles={{ 
            body: { 
              padding: '24px'
            } 
          }}
        >
          {/* Search form */}
          <Form 
            form={form}
            onFinish={handleSearch} 
            layout="inline" 
            style={{ marginBottom: '24px' }}
          >
            <Form.Item name="dateRange" label="日期时间">
              <RangePicker />
            </Form.Item>
            <Form.Item>
              <Space>
                <Button type="primary" htmlType="submit" icon={<SearchOutlined />} loading={loading}>
                  搜索
                </Button>
                <Button onClick={handleReset} loading={loading}>
                  重置
                </Button>
              </Space>
            </Form.Item>
          </Form>
          
          <ProTable
            dataSource={dataSource}
            columns={columns}
            rowKey="key"
            pagination={{
              pageSize: 10,
            }}
            search={false}
            options={{
              setting: false,
              fullScreen: false,
              reload: false,
              density: false,
            }}
            bordered
            loading={loading}
          />
        </Card>
      </div>
    </div>
  );
};

export default WorkDetail;